package com.sh.rbac.core.encrypt.filter.wrapper;

import cn.hutool.core.io.IoUtil;
import com.sh.rbac.core.encrypt.util.EncryptUtils;
import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import org.springframework.http.MediaType;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * 请求体解密包装器
 *
 * @author wb
 * @since 2025-10-23
 */
public class DecryptRequestBodyWrapper extends HttpServletRequestWrapper {

    private final byte[] body;


    public DecryptRequestBodyWrapper(HttpServletRequest request, String encryptHeader, String privateKey) throws IOException {
        super(request);
        // 解密请求头中的 AES 密钥
        String base64AesKey = EncryptUtils.decryptByRsa(encryptHeader, privateKey);
        String aesKey = EncryptUtils.decryptByBase64(base64AesKey);

        // 解密请求体
        byte[] readBytes = IoUtil.readBytes(request.getInputStream(), false);
        String requestBody = new String(readBytes, StandardCharsets.UTF_8);
        String decryptBody = EncryptUtils.decryptByAes(requestBody, aesKey);

        this.body = decryptBody.getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        return new ServletInputStream() {
            private final InputStream inputStream = new ByteArrayInputStream(body);

            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return inputStream.read();
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
    }

    @Override
    public String getContentType() {
        return MediaType.APPLICATION_JSON_VALUE;
    }

    @Override
    public int getContentLength() {
        return body.length;
    }
}
